<?php

require_once '../swift-mailer/lib/swift_required.php';

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				//$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				//mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
				  ->setUsername('ktlqai@gmail.com')
				  ->setPassword('aiEffortGoogle')
				  ;
				$mailer = Swift_Mailer::newInstance($transport);
  				$message = Swift_Message::newInstance()

				  // Give the message a subject
				  ->setSubject($model->subject)
				
				  // Set the From address with an associative array
				  ->setFrom(array($model->email => $model->name))
				
				  // Set the To addresses with an associative array
				  ->setTo(array('ktlqai@yahoo.com', 'ktlqai@gmail.com' => 'Ai Le'))
				
				  // Give it a body
				  ->setBody($model->body)
				
				  ;
				$result = $mailer->send($message);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}
	
	public function actionForgotPassword()
	{
		$model=new ForgotPasswordForm;
		if(isset($_POST['ForgotPasswordForm']))
		{
			$model->attributes=$_POST['ForgotPasswordForm'];
			if($model->validate())
			{
				//$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				//mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
				  ->setUsername('ktlqai@gmail.com')
				  ->setPassword('aiEffortGoogle')
				  ;
				$mailer = Swift_Mailer::newInstance($transport);
  				$user=User::model()->find('email=:email', array(':email'=>$model->email));
				$password = $this->generateSalt(6);
				$hashedPassword = md5($user->salt.$password);
				$user->password=$hashedPassword;
				$user->save();
				$message = Swift_Message::newInstance()

				  // Give the message a subject
				  ->setSubject('Password Reset')
				
				  // Set the From address with an associative array
				  ->setFrom(array('ktlqai@gmail.com' => 'Ai Le'))
				
				  // Set the To addresses with an associative array
				  ->setTo(array($model->email => $user->username))
				
				  // Give it a body
				  ->setBody('Hi '.$user->username.'
Your new password: "'.$password.'"');
				
				  ;
				$result = $mailer->send($message);
				Yii::app()->user->setFlash('forgotpassword','Reset password has been e-mailed to you.');
				$this->refresh();
			}
		}
		$this->render('forgotpassword',array('model'=>$model));
	}
	
	function generateSalt($length=32){
		$string = "";
		$possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		
		for($i=0;$i < $length;$i++) {
			$char = $possible[mt_rand(0, strlen($possible)-1)];
			$string .= $char;
		}
		
		return $string;
	}
	
	public function actionRegister()
	{
		$model=new RegisterForm;
		if(isset($_POST['RegisterForm']))
		{
			$model->attributes=$_POST['RegisterForm'];
			if($model->validate())
			{
				$user = new User;
				$user->username = $model->username;
				//$user->password = $model->password;
				$user->email = $model->email;
				$user->profile = $_POST['RegisterForm']['profile']; // ? profile not found
				$user->salt = $this->generateSalt();
				$user->password = md5($user->salt.$model->password);
				if ($user->save())
					Yii::app()->user->setFlash('register','Thank you for registering.'); // ? login link
				else
					Yii::app()->user->setFlash('register','Registering failed.'); // ? login link
				$this->refresh();
			}
		}
		$this->render('register',array('model'=>$model));
	}
	
	public function actionUserSettings()
	{
		$model=new UserSettingsForm;
		$user = User::model()->findByPk(Yii::app()->user->id);
		if(isset($_POST['UserSettingsForm']))
		{
			$model->attributes=$_POST['UserSettingsForm'];
			if($model->validate())
			{
				//$user = User::model()->findByPk(Yii::app()->user->id);
				//$user->username = $model->username;
				//$user->password = $model->password;
				//$user->email = $model->email;
				$user->profile = $_POST['UserSettingsForm']['profile']; // ? profile not found SOLVED
				//$user->salt = $this->generateSalt();
				$user->password = md5($user->salt.$model->new_password);
				if ($user->save())
					Yii::app()->user->setFlash('usersettings','User settings success.'); // ? login link
				else
					Yii::app()->user->setFlash('usersettings','User settings failed.'); // ? login link
				$this->refresh();
			}
		}
		$model->profile = $user->profile;
		$this->render('usersettings',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}